package com.zengdw.logRecord.resolve;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义函数工厂
 *
 * @author zengd
 * @date 2021/9/18 10:26
 */
public class ParseFunctionFactory {
    private Map<String, IParseFunction> allFunMap;

    public ParseFunctionFactory(List<IParseFunction> parseFunctions) {
        if (CollectionUtils.isEmpty(parseFunctions)) {
            return;
        }
        allFunMap = new HashMap<>();
        parseFunctions.stream().filter(f -> StringUtils.hasText(f.functionName()))
                .forEach(f -> allFunMap.put(f.functionName(), f));
    }

    public boolean isBeforeFunction(String functionName) {
        if(StringUtils.isEmpty(functionName)) {
            return false;
        }
        return allFunMap.get(functionName) != null && allFunMap.get(functionName).executeBefore();
    }

    public String apply(String functionName, Object... values) {
        IParseFunction parseFunction = allFunMap.get(functionName);
        if(null == parseFunction) {
            return "";
        }
        return parseFunction.apply(values);
    }
}
